import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
//导入element-plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
//导入axios
import axios from 'axios'
import qs from 'qs'
//配置基础路径
axios.defaults.baseURL = 'http://localhost:9000'
const app = createApp(App)
//指定全局对象
app.config.globalProperties.$axios = axios
app.config.globalProperties.$qs = qs
//使用element
app.use(ElementPlus)
app.use(router).mount('#app')


//请求拦截器
axios.interceptors.request.use( req => {
    console.log('拦截请求',req)
    //读取token
    let token = localStorage.getItem('token')
    //如果不为空，就添加到请求头中
    if(token){
        req.headers.Authorization = token
    }
    return req
})
import {ElMessageBox} from "element-plus";
//响应拦截器
axios.interceptors.response.use( resp => {
    console.log('拦截响应',resp)
    //判断响应内容中没有token报错信息
    if(resp.data === 'Token is wrong!' || resp.data === 'Token is empty!'){
        //给用户提示，强制登录
        ElMessageBox.alert('没有权限，请重新登录', '访问错误', {
            confirmButtonText: 'OK'
        }).then(() => {
            //强制跳转登录界面
            location.href="/"
        })
    }
    return resp
})